tool
extends Resource

class_name TileTypeMap

var tile_type_array: Array = []
var tile_type_map: Dictionary = {}

func update_tile_type_map():
	tile_type_map = {}
	for obj in tile_type_array:
		var tile_type: TileType = obj as TileType
		if tile_type != null and not tile_type.id.empty():
			tile_type_map[tile_type.id] = tile_type

func lookup(id: String) -> TileType:
	if id.empty():
		return null
	if tile_type_map.empty() and tile_type_array.size() > 0:
		update_tile_type_map()
	if tile_type_map.has(id):
		return tile_type_map[id]
	else:
		printerr("[TileTypeMap::lookup] tile type '%s' not found!" % id)
		return null

func _get_idx_from_name(name: String) -> int:
	var subname = name.substr(11)
	if subname.is_valid_integer():
		return int(subname)
	return -1

func _get_property_list():
	var prop_list: Array = []

	prop_list.append({
		name = "tile_types/count",
		type = TYPE_INT,
		hint_string = "0,100,1,or_greater",
	})

	for i in range(tile_type_array.size()):
		prop_list.append({
			name = "tile_types/" + str(i),
			type = TYPE_OBJECT,
			hint = PROPERTY_HINT_RESOURCE_TYPE,
			hint_string = "TileType",
		})

	return prop_list

func _get(property: String):
	if property == "tile_types/count":
		return tile_type_array.size()
	elif property.begins_with("tile_types/"):
		var idx = _get_idx_from_name(property)
		if idx >= 0 and idx < tile_type_array.size():
			return tile_type_array[idx]

func _set(property: String, value):
	if property == "tile_types/count":
		if value < 0:
			value = 0
		if value == tile_type_array.size():
			return
		if value > tile_type_array.size():
			while value > tile_type_array.size():
				tile_type_array.append(null)
		elif value < tile_type_array.size():
			while value < tile_type_array.size() and tile_type_array.size() > 0:
				tile_type_array.remove(tile_type_array.size() - 1)
		property_list_changed_notify()
	elif property.begins_with("tile_types/"):
		var idx = _get_idx_from_name(property)
		if idx >= 0:
			while idx >= tile_type_array.size():
				tile_type_array.append(null)
			tile_type_array[idx] = value
